<?php

  class JooS_Server_Presentation {
    private static $_selfReflection = null;

    private static $_extendedReflections = array();

    private $_request = null;

    private $_name = null;

    private $_message = null;
    
    public function __construct($name) {
      $this->_name = $name;
    }

    public function getRequest() {
      if (is_null($this->_request))
        $this->_request = JooS_Server::getInstance()->getRequest();
      return $this->_request;
    }

    public function getContentType() {
      return "application/octet-stream";
    }

    function getBody($resource) {
      return $this->_name;
    }

    final public static function factory($name) {
      $name = strtolower($name);
      if (is_null(self::$_selfReflection))
        self::$_selfReflection = new ReflectionClass(__CLASS__);

      if (isset(self::$_extendedReflections[$name])) {
        $rClass = self::$_extendedReflections[$name];
      }
      else {
        $className = __CLASS__ . str_replace(" ", "_", ucwords(str_replace("-", " ", "-" . $name)));

        try {
          try {
            @Zend_Loader::loadClass($className);

            $rClass = new ReflectionClass($className);
            if (!$rClass->isSubclassOf(self::$_selfReflection))
              self::throwException("Presentation '$className' must extend " . __CLASS__);
          }
          catch (Zend_Exception $e) {
            self::throwException("Presentation '$name' was not found", 503);
          }
        }
        catch (JooS_Server_Presentation_Exception $e) {
          $rClass = self::$_selfReflection;
        }
        if (!$rClass->isInstantiable())
          self::throwException("Presentation '$name' can not be used", 503);

        self::$_extendedReflections[$name] = $rClass;
      }
      return $rClass->newInstance($name);
    }

    protected static function throwException($message, $code = 0) {
      require_once "JooS/Server/Presentation/Exception.php";

      throw new JooS_Server_Presentation_Exception($message, $code);
    }
  }

?>